package com.sgb.kjwl.view.ui.activity.leaseAsk.fragment;

import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.FragmentAskLeaseFactory2Binding;
import com.sgb.kjwl.model.entity.AskLeaseFactoryEntity;
import com.sgb.kjwl.model.entity.AskLeaseFarmEntity;
import com.sgb.kjwl.utils.EditInputFilter;
import com.sgb.kjwl.viewmodel.machine.AskLeaseCommonModel;
import com.sgb.kjwl.viewmodel.machine.AskLeaseFactoryModel2;
import com.swgk.core.customview.CfkEditView;
import com.swgk.core.util.MToast;
import com.swgk.core.util.PickSelectEntity;

import java.util.ArrayList;
import java.util.List;

public class AskLeaseFactoryFragment2 extends Fragment {

    private FragmentAskLeaseFactory2Binding binding;
    private AskLeaseFactoryModel2 viewModel;
    private AskLeaseCommonModel commonModel;

    private List<PickSelectEntity> invoiceGGDatas = new ArrayList<>();//发票类型
    private List<PickSelectEntity> shuilvDatas = new ArrayList<>();//税率
    private OptionsPickerView pickerView1, pickerView2;
    private List<AskLeaseFactoryEntity.ParamBean> viewList = new ArrayList<>();//自定义参数
    private String id = "";


    public void onAttach(Context context) {
        super.onAttach(context);
        id = getArguments().getString("id");
    }

    public static AskLeaseFactoryFragment2 newInstance(String id) {
        AskLeaseFactoryFragment2 frag = new AskLeaseFactoryFragment2();
        Bundle bundle = new Bundle();
        bundle.putString("id", id);
        frag.setArguments(bundle);
        return frag;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_ask_lease_factory_2, container, false);
        binding.setLifecycleOwner(this);
        return binding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        viewModel = new ViewModelProvider(getActivity()).get(AskLeaseFactoryModel2.class);
        commonModel = new ViewModelProvider(this).get(AskLeaseCommonModel.class);
        initView();
        receiverLiveData();
        initData();
        showDetail();
    }

    private void initData() {
        invoiceGGDatas = commonModel.getInvoiceData();
        commonModel.getLeaseRate();
        showPop1();
        showPop2();

    }

    private void receiverLiveData() {
        commonModel.showRateLiveData.observe(getViewLifecycleOwner(), t -> shuilvDatas.addAll(t));

    }

    private void initView() {
        binding.beforeAndNextStepItem.tvNextStep.setOnClickListener(v -> {
            if (checkInput()) {
                viewModel.selectFragLiveData.postValue(2);
            }
        });
        binding.beforeAndNextStepItem.tvSubmit.setOnClickListener(v -> {
            if (checkInput()) {
                viewModel.addOrupdate(viewModel.entity);
            }
        });
        binding.beforeAndNextStepItem.tvBeforeStep.setOnClickListener(v -> viewModel.selectFragLiveData.postValue(0));
        binding.itvInvoiceType.setOnWholeItemClickListener(view -> pickerView1.show());
        binding.itvShuiLv.setOnWholeItemClickListener(view -> pickerView2.show());
        binding.tvAddView.setOnClickListener(v -> addView());
        binding.tvDelView.setOnClickListener(v -> delView());
        binding.marginMoney.setFilters(new EditInputFilter[]{new EditInputFilter(99999999, 1, 0)});
    }

    /**
     * 发票类型
     */
    private void showPop1() {
        pickerView1 = new OptionsPickerBuilder(getActivity(), (options1, options2, options3, v) -> {
            String content = invoiceGGDatas.get(options1).getProjectscale();
            binding.itvInvoiceType.setContent(content);
            viewModel.entity.getAttach().setInvoiceType(invoiceGGDatas.get(options1).getNo());
            if ("不需要发票".equals(content)) {
                binding.itvShuiLv.setVisibility(View.GONE);
            } else {
                binding.itvShuiLv.setVisibility(View.VISIBLE);
            }
        }).build();
        pickerView1.setPicker(invoiceGGDatas);
        pickerView1.setSelectOptions(0);
    }

    /**
     * 税率
     */
    private void showPop2() {
        pickerView2 = new OptionsPickerBuilder(getActivity(), (options1, options2, options3, v) -> {
            binding.itvShuiLv.setContent(shuilvDatas.get(options1).getProjectscale());
            viewModel.entity.getAttach().setTariff(shuilvDatas.get(options1).getNo());
        }).build();
        pickerView2.setPicker(shuilvDatas);
        pickerView2.setSelectOptions(0);
    }


    private void addView() {
        if (binding.llDescGroup.getChildCount() >= 5) {
            MToast.showToast(getActivity(), "最多只能新增5条");
            return;
        }
        if (!getViewList()) {
            return;
        }
        View view = View.inflate(getActivity(), R.layout.layout_lease_ask_item, null);
        binding.llDescGroup.addView(view, binding.llDescGroup.getChildCount());
        TextView tvDel = view.findViewById(R.id.tv_del);
        tvDel.setOnClickListener(view1 -> binding.llDescGroup.removeView(view));
        if (binding.llDescGroup.getChildCount() > 1) {
            View itemView = binding.llDescGroup.getChildAt(binding.llDescGroup.getChildCount() - 2);
            itemView.findViewById(R.id.tv_del).setVisibility(View.VISIBLE);
        }
        binding.tvDelView.setVisibility(View.VISIBLE);
    }

    private void delView() {
        if (binding.llDescGroup.getChildCount() > 0) {
            binding.llDescGroup.removeViewAt(binding.llDescGroup.getChildCount() - 1);
            if (binding.llDescGroup.getChildCount() == 0) {
                binding.tvDelView.setVisibility(View.GONE);
            } else {
                View itemView = binding.llDescGroup.getChildAt(binding.llDescGroup.getChildCount() - 1);
                itemView.findViewById(R.id.tv_del).setVisibility(View.GONE);
            }
        }

    }

    public boolean getViewList() {
        viewList.clear();
        for (int i = 0; i < binding.llDescGroup.getChildCount(); i++) {
            View view = binding.llDescGroup.getChildAt(i);
            String title = ((EditText) view.findViewById(R.id.tv_desc_title)).getText().toString().trim();
            String content = ((CfkEditView) view.findViewById(R.id.tv_desc_content)).getEditContent().trim();
            if (TextUtils.isEmpty(title) || TextUtils.isEmpty(content)) {
                MToast.showToast(getActivity(), "请完善新增说明");
                return false;
            }
            AskLeaseFactoryEntity.ParamBean bean = new AskLeaseFactoryEntity.ParamBean();
//            bean.setNo(i);
            bean.setTitle(title);
            bean.setContent(content);
            viewList.add(bean);
        }
        return true;
    }

    public boolean getViewList2() {
        viewList.clear();
        for (int i = 0; i < binding.llDescGroup.getChildCount(); i++) {
            View view = binding.llDescGroup.getChildAt(i);
            String title = ((EditText) view.findViewById(R.id.tv_desc_title)).getText().toString().trim();
            String content = ((CfkEditView) view.findViewById(R.id.tv_desc_content)).getEditContent().trim();
            if (TextUtils.isEmpty(title) && !TextUtils.isEmpty(content)) {
                MToast.showToast(getActivity(), "请完善新增说明");
                return false;
            }
            if (!TextUtils.isEmpty(title) && TextUtils.isEmpty(content)) {
                MToast.showToast(getActivity(), "请完善新增说明");
                return false;
            }
            if (!TextUtils.isEmpty(title) && !TextUtils.isEmpty(content)) {
                AskLeaseFactoryEntity.ParamBean bean = new AskLeaseFactoryEntity.ParamBean();
                //bean.setNo(i);
                bean.setTitle(title);
                bean.setContent(content);
                viewList.add(bean);
            }
        }
        return true;
    }

    private void showDetail() {
        if (!TextUtils.isEmpty(id)) {
            binding.marginMoney.setText(viewModel.entity.getAttach().getPerformanceBond());
            binding.cetFactoryUtilities.setEditContent(viewModel.entity.getAttach().getFactoryUtilities());
            binding.cetDormFee.setEditContent(viewModel.entity.getAttach().getDormFee());
            binding.cetDormUtilities.setEditContent(viewModel.entity.getAttach().getDormUtilities());
            binding.cetManageFee.setEditContent(viewModel.entity.getAttach().getManageFee());
            if ("0".equals(viewModel.entity.getAttach().getInvoiceType())) {
                binding.itvInvoiceType.setContent("普通发票");
                binding.itvShuiLv.setVisibility(View.VISIBLE);
                binding.itvShuiLv.setContent(viewModel.entity.getAttach().getTariff() + "%");
            } else if ("1".equals(viewModel.entity.getAttach().getInvoiceType())) {
                binding.itvInvoiceType.setContent("专用发票");
                binding.itvShuiLv.setVisibility(View.VISIBLE);
                binding.itvShuiLv.setContent(viewModel.entity.getAttach().getTariff() + "%");
            } else {
                binding.itvInvoiceType.setContent("不需要发票");
                binding.itvShuiLv.setVisibility(View.GONE);//不需要发票时隐藏税率
            }
            //附加字段返显
            if (viewModel.entity.getAttach().getExtra() != null && viewModel.entity.getAttach().getExtra().size() > 0) {
                for (int i = 0; i < viewModel.entity.getAttach().getExtra().size(); i++) {
                    AskLeaseFactoryEntity.ParamBean param = viewModel.entity.getAttach().getExtra().get(i);
                    View view = View.inflate(getActivity(), R.layout.layout_lease_ask_item, null);
                    ((EditText) view.findViewById(R.id.tv_desc_title)).setText(param.getTitle());
                    ((CfkEditView) view.findViewById(R.id.tv_desc_content)).setEditContent(param.getContent());
                    binding.llDescGroup.addView(view, i);
                    //删除按钮
                    TextView tvDel = (TextView) view.findViewById(R.id.tv_del);
                    tvDel.setVisibility(View.VISIBLE);
                    tvDel.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            binding.llDescGroup.removeView(view);
                        }
                    });
                    if (i == viewModel.entity.getAttach().getExtra().size() - 1) {
                        tvDel.setVisibility(View.GONE);
                        binding.tvAddView.setVisibility(View.VISIBLE);
                        binding.tvDelView.setVisibility(View.VISIBLE);
                    }
                }
            }
        }
    }

    private boolean checkInput() {
        if (binding.itvShuiLv.getVisibility() == View.VISIBLE && TextUtils.isEmpty(binding.itvShuiLv.getContent())) {
            MToast.showToast(getActivity(), "请选择税率");
            return false;
        }
        if (getViewList2()) {
            viewModel.entity.getAttach().setExtra(viewList);
        } else {
            return false;
        }
        viewModel.entity.getAttach().setPerformanceBond(binding.marginMoney.getText().toString().trim());
        viewModel.entity.getAttach().setFactoryUtilities(binding.cetFactoryUtilities.getEditContent());
        viewModel.entity.getAttach().setDormFee(binding.cetDormFee.getEditContent());
        viewModel.entity.getAttach().setDormUtilities(binding.cetDormUtilities.getEditContent());
        viewModel.entity.getAttach().setManageFee(binding.cetManageFee.getEditContent());
        return true;
    }


}
